﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Web.Security;

using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

using PTUDW_CNTN2010_F_CDT.Models;

namespace PTUDW_CNTN2010_F_CDT.Controllers
{
    public class AccountController : Controller
    {
        private static OpenIdRelyingParty openid = new OpenIdRelyingParty();

        private EcommerceDBContext db = new EcommerceDBContext();

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LogInModel account, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (isValidAccount(account.UserName, account.Password))
                {
                    FormsAuthentication.SetAuthCookie(account.UserName, false);

                    return Redirect(returnUrl);
                }
            }
            else
            {
                ModelState.AddModelError("", "Tai khoan hoac mat khau khong dung");
            }

            return View(account);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Register()
        {
            ViewBag.ProvinceId = new SelectList(db.Provinces, "ProvinceId", "ProvinceName");
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                bool accountExist = db.Customers.Any(c => c.UserName == model.UserName);
                Customer customer = new Customer
                {
                    UserName = model.UserName,
                    Password = model.Password,
                    Email = model.Email,
                    FullName = model.FullName,
                    Address = model.Address,
                    Phone = model.Phone,
                    Sex = model.Sex,
                    IsActive = false,
                    ProvinceId = model.ProvinceId,
                };
                if (!accountExist)
                {
                    db.Customers.Add(customer);
                    db.SaveChanges();

                    FormsAuthentication.SetAuthCookie(customer.UserName, false);
                }
                else
                {
                    ModelState.AddModelError("", "Ten dang nhap da ton tai");
                }
            }

            ViewBag.ProvinceId = new SelectList(db.Provinces, "ProvinceId", "ProvinceName");

            return View(model);
        }

        private bool isValidAccount(string userName, string password)
        {
            return db.Customers.Any(c => c.UserName == userName && c.Password == password);
        }

        [ValidateInput(false)]
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                //Let us submit the request to OpenID provider
                Identifier id;
                string temp = "https://www.google.com/accounts/o8/id";
                //string s = Request.Form["openid_identifier"].ToString();
                if (Identifier.TryParse("https://www.google.com/accounts/o8/id", out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(temp);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewBag.Message = ex.Message;
                        return View("LogOn");
                    }
                }

                ViewBag.Message = "Invalid identifier";
                return View("LogOn");
            }

            switch (response.Status)
            {

                case AuthenticationStatus.Authenticated:
                    FormsAuthentication.SetAuthCookie("google", false);
                    return View("LogIn");

                case AuthenticationStatus.Canceled:
                    ViewBag.Message = "Canceled at provider";
                    return View("LogIn");
                case AuthenticationStatus.Failed:
                    ViewBag.Message = response.Exception.Message;
                    return View("LogIn");
            }

            return new EmptyResult();
        }
    }
}
